import * as vscode from 'vscode';
import { DraftManager } from '../../services/draftManager';
import { getAllMarkdownFiles } from '../../utils/fileUtils';

export class MarkdownNode extends vscode.TreeItem {
    public title: string=""; // Add title property

    constructor(
        public readonly resourceUri: vscode.Uri,
        public readonly collapsibleState: vscode.TreeItemCollapsibleState,
        public readonly isDirectory: boolean = false
    ) {
        super(resourceUri, collapsibleState);
        this.tooltip = this.resourceUri.fsPath;
        this.contextValue = isDirectory ? 'directory' : 'file';

        if (!isDirectory) {
            this.command = {
                command: 'markdownExplorer.openFile',
                title: 'Open File',
                arguments: [this.resourceUri]
            };
        }
    }
}

export class MarkdownNodeProvider implements vscode.TreeDataProvider<MarkdownNode> {
    private _onDidChangeTreeData: vscode.EventEmitter<MarkdownNode | undefined | null | void> = new vscode.EventEmitter<MarkdownNode | undefined | null | void>();
    readonly onDidChangeTreeData: vscode.Event<MarkdownNode | undefined | null | void> = this._onDidChangeTreeData.event;

    constructor(
        private workspaceRoot: string,
        private draftManager: DraftManager
    ) {
        // 监听文件系统变化
        const watcher = vscode.workspace.createFileSystemWatcher(
            new vscode.RelativePattern(workspaceRoot, '**/*.md')
        );

        watcher.onDidCreate(() => this.refresh());
        watcher.onDidChange(() => this.refresh());
        watcher.onDidDelete(() => this.refresh());
    }

    refresh(): void {
        this._onDidChangeTreeData.fire();
    }

    getTreeItem(element: MarkdownNode): vscode.TreeItem {
        return element;
    }

    async getChildren(element?: MarkdownNode): Promise<MarkdownNode[]> {
        if (!this.workspaceRoot) {
            return Promise.resolve([]);
        }

        if (element) {
            const files = await getAllMarkdownFiles(element.resourceUri.fsPath);
            return this.createNodes(files);
        } else {
            const files = await getAllMarkdownFiles(this.workspaceRoot);
            return this.createNodes(files);
        }
    }

    private async createNodes(files: vscode.Uri[]): Promise<MarkdownNode[]> {
        try {
            const sortedFiles = files.sort((a, b) => {
                const fileNameA = vscode.workspace.asRelativePath(a, false).toLowerCase();
                const fileNameB = vscode.workspace.asRelativePath(b, false).toLowerCase();
                return fileNameA.localeCompare(fileNameB);
            });
            const nodes = await Promise.all(sortedFiles.map(file => this.createMarkdownNode(file)));

            return nodes.sort((a, b) => {
                const aIsDraft = a.contextValue === 'markdownFileDraft';
                const bIsDraft = b.contextValue === 'markdownFileDraft';
                if (aIsDraft !== bIsDraft) {
                    return bIsDraft ? -1 : 1; // Drafts first
                }
                // Then sort by title alphabetically within each group
                return a.title.localeCompare(b.title);
            });
        } catch (error) {
            console.error('Error creating nodes:', error);
            return [];
        }
    }

    private async createMarkdownNode(file: vscode.Uri): Promise<MarkdownNode> {
        const md_file = this.draftManager.getMdFile(file);
        if (!md_file) {
            return new MarkdownNode(
                file,
                vscode.TreeItemCollapsibleState.None,
                false
            );
        }
        const isDraft = md_file.isDraft();
        const isInCache = await this.draftManager.isInCache(file);
        const title = md_file.getTitle();
        const node = new MarkdownNode(
            file,
            vscode.TreeItemCollapsibleState.None,
            false
        );

        // 设置上下文值，用于右键菜单等功能
        if (isInCache) {
            node.contextValue = isDraft ? 'markdownFileDraftCached' : 'markdownFileCached';
        } else {
            node.contextValue = isDraft ? 'markdownFileDraft' : 'markdownFile';
        }

        node.tooltip = `${vscode.workspace.asRelativePath(file, false)}`;    // hover 显示完整路径

        // 设置标签显示
        if (isDraft) {
            node.label = { label: `${title}`, highlights: [[0, title.length]] };
        } else {
            node.label = title;
        }

        // 设置图标和颜色
        // 缓存状态优先：如果文件在缓存中，显示为绿色；否则，如果是草稿，显示为黄色
        if (isInCache) {
            // 在缓存中的文件显示为绿色
            node.iconPath = new vscode.ThemeIcon('check', new vscode.ThemeColor('terminal.ansiGreen'));
        } else if (isDraft) {
            // 草稿文件显示为黄色
            node.iconPath = new vscode.ThemeIcon('error', new vscode.ThemeColor('problemsErrorIcon.foreground'));
        } else {
            // 普通文件
            node.iconPath = new vscode.ThemeIcon('info');
        }

        node.title = title;
        return node;
    }
}